/*
* created by kaweepapkongkittisan
*
*/


package com.tuinui.trade.controller.job;

import com.tuinui.trade.*;
import com.tuinui.trade.entry.StockTradeDailyEntry;
import com.tuinui.trade.manager.DataManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
public class JobController {
    final public static Logger _log = LoggerFactory.getLogger(JobController.class);

    @RequestMapping(value="/hello", method=RequestMethod.GET)
	public ModelAndView hello(){
		ModelAndView mv = new ModelAndView("hello");

		return mv;
	}
    @RequestMapping(value="/price-db", method=RequestMethod.GET)
    public ModelAndView savePriceToDB()throws Exception{
        ModelAndView mv = new ModelAndView("price");
        Map<String, StockTradeDailyEntry> entries = DataManager.getInstance().getCachedPrice();
        _log.debug("clean old stock price from database .....");

        DataManager.getInstance().cleanPrice();
        ArrayList a = new ArrayList<StockTradeDailyEntry>();
        a.addAll(entries.values());
        _log.debug("Saving stock price to database .....");

        DataManager.getInstance().savePriceList(a);
        _log.debug("Saved stock price to database .....");

        mv.addObject("priceList", a);
        return mv;

    }
    @RequestMapping(value="/robot*", method=RequestMethod.POST)
    public String robot(){

        return "";

    }


    @RequestMapping(value="/price-live", method=RequestMethod.GET)
	public ModelAndView listPriceOnline()throws Exception{
		ModelAndView mv = new ModelAndView("price");
		String setUrl = "http://marketdata.set.or.th/mkt/aomstocklistresult.do?tradingMethod=aomstocklistresult.do&market=SET&language=th&country=TH";
		String maiUrl = "http://marketdata.set.or.th/mkt/aomstocklistresult.do?tradingMethod=aomstocklistresult.do&market=mai&language=th&country=TH";

		IStockPriceDownloader downloader = new StockPriceDownloaderAppengineImpl();
		downloader.setSource(new String[]{setUrl, maiUrl});
		List<StockTradeDailyEntry> entries = new ArrayList<StockTradeDailyEntry>();
		downloader.downloadSource();
		entries = downloader.extractStockPrice();

        _log.debug("Saving stock price to cache .....");
        DataManager.getInstance().setPriceCache(entries);
        _log.debug("Saved stock price to cache .....");
		mv.addObject("priceList", entries);

        _log.debug("number of stocks: " + entries.size());
		
		return mv;
	}

}
